package org.wutopia.labcloud.domain.uaa.config.websocket;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketHandler extends TextWebSocketHandler {


    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("新连接建立: " + session.getId());
        session.sendMessage(new TextMessage("欢迎连接 WebSocket 服务器！"));
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        String payload = message.getPayload();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(payload);

        // 直接获取字段值
        String authValue = rootNode.get("userId").asText();
        System.out.println("userId: " + authValue);

        sessions.put(authValue, session);
        System.out.println("收到消息: " + message.getPayload());
        session.sendMessage(new TextMessage("服务器收到: " + message.getPayload()));
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭: " + session.getId());
        sessions.remove(session.getId());
    }


    public static boolean sendMsg(Long userId, String msg) throws IOException {
        WebSocketSession webSocketSession = sessions.get(userId.toString());
        if(webSocketSession != null) {
            webSocketSession.sendMessage(new TextMessage(msg));
            return true;
        }
        return false;
    }

}